<template>
  <view class="applicationSeal">
    <u-form ref="uForm" :model="form" label-width="160">
      <!-- <u-form-item label="印章类型" prop="sealType" required>
        <u-radio-group v-model="form.sealType" @change="changeSealType" >
          <u-radio name="entity"> 加盖实体章</u-radio>
          <u-radio name="electron"> 加盖电子章</u-radio>
        </u-radio-group>
      </u-form-item> -->
      <u-form-item v-show="form.title" :label="$t('申请单名称')" prop="title" required>
        <u-input v-model="form.title" border disabled />
      </u-form-item>
      <u-form-item
        :border-bottom="contractList.length <= 0"
        :label="$t('待盖章合同')"
        prop="contractId"
        required
      >
        <u-tag
          v-for="(item, index) in contractList"
          :key="index"
          :text="item.title"
          closeable
          type="success"
          @close="delContract(item.id)"
        />
        <u-button
          v-if="contractList.length !== 1"
          slot="right"
          size="mini"
          type="primary"
          @click="addElectronContract"
        >
          + {{$t('选择电子合同')}}
        </u-button>
      </u-form-item>
      <u-form-item :label="$t('所属企业')" prop="enterpriseName" required>
        <u-input
          v-model="form.enterpriseName"
          :select-open="select.title === '所属企业' && select.show"
          border
          type="select"
          @clear="inputSelect('所属企业')"
          @click="showSelect('所属企业')"
        />
      </u-form-item>
      <template v-if="form.enterpriseId">
        <u-form-item label="加盖电子章" prop="sealName" required>
          <u-input
            v-model="form.sealName"
            :select-open="select.title === '加盖电子章' && select.show"
            border
            type="select"
            @clear="inputSelect('加盖电子章')"
            @click="showSelect('加盖电子章')"
          />
        </u-form-item>
      </template>
      <template v-if="form.sealId">
        <u-form-item :label="$t('审批方式')" prop="type" required>
          <u-radio-group v-model="form.type">
            <u-radio name="process">{{$t('审批流程')}}</u-radio>
            <u-radio name="user">{{$t('审批人')}}</u-radio>
          </u-radio-group>
        </u-form-item>
        <template v-if="form.type === 'process' && form.isShowDepartment">
          <u-form-item :label="$t('审批流程')" prop="processName" required>
            <u-input
              v-model="form.processName"
              :select-open="select.show"
              border
              type="select"
              @clear="deleteAuditProcessFn()"
              @click="showSelect('选择审批流程')"
            />
          </u-form-item>
          <u-form-item v-if="form.departmentName" :label="$t('组织')" prop="departmentName" required>
            <u-input
              v-model="form.departmentName"
              :clearable="false"
              :select-open="select.show"
              border
              type="select"
              @click="showSelect('选择组织')"
            />
          </u-form-item>
        </template>
        <template v-else>
          <u-form-item
            :border-bottom="managerList.length > 0 ? false : true"
            :label="$t('审批人')"
            prop="auditUser"
            required
          >
            <u-button slot="right" size="mini" type="primary" @click="secrecy_seal('电子章审批人')">
              {{$t('选取')}}
            </u-button>
          </u-form-item>
          <u-form-item v-if="managerList.length > 0">
            <uni-list :border="false" style="width: 720rpx">
              <uni-list-item
                v-for="(item, index) in managerList"
                :key="index"
                :border="false"
                :ellipsis="1"
                :title="item.label"
                clickable
              >
                <view slot="footer" style="color: #888">
                  <u-icon
                    name="close-circle"
                    size="40"
                    style="margin-left: 20rpx"
                    @click="delManagerList(item.key)"
                  ></u-icon>
                </view>
              </uni-list-item>
            </uni-list>
          </u-form-item>
        </template>
      </template>

      <u-form-item :label="$t('加盖次数')" prop="useCount" required>
        <u-number-box v-model="form.useCount" :min="1"></u-number-box>
      </u-form-item>
      <u-form-item :label="$t('申请说明')" prop="remark">
        <u-input v-model="form.remark" border type="textarea" />
      </u-form-item>
    </u-form>

    <u-select
      v-model="select.show"
      :filterable="select.filterable"
      :label-name="select.label"
      :list="select.list"
      :value-name="select.value"
      @confirm="confirmSelet"
    ></u-select>
    <!-- 选取组织 -->
    <u-picker
      v-model="picker.show"
      :default-selector="[0]"
      :mask-close-able="false"
      :range="picker.data"
      mode="selector"
      range-key="name"
      safe-area-inset-bottom
      :title="$t('选择组织')"
      @cancel="pickerCancel"
      @confirm="pickerConfirm"
    ></u-picker>
    <!-- #ifdef MP-WEIXIN -->
    <view class="submissionbtn">
      <u-button :loading="!btnOnoff" size="medium" type="primary" @click="submission">
        {{$t('立即提交')}}
      </u-button>
    </view>
    <!-- #endif -->
  </view>
</template>

<script>
import { mapGetters, mapMutations } from 'vuex'

export default {
  computed: {
    ...mapGetters(['userInfo', 'api', 'userToken']),
    //计算图片属性
    computedFileType() {
      return (item) => {
        return this.$lizhao.file.lzGetFileType(item.type)
      }
    }
  },
  components: {},
  data() {
    return {
      btnOnoff: true, //控制多次提交
      form: {
        sealType: 'electron', //electron电子章，entity实体章
        title: '', //用章文件名
        enterpriseId: '', //企业id
        enterpriseName: '', //所属企业名
        sealId: '', //实体章id
        sealName: '', //实体章名
        contractId: '', //合同id
        type: 'process', //审批方式process为审批流程 user审批人
        processId: '', //审批流程id
        managerIds: '', //审批人ids
        isShowDepartment: true, //当选取的审批流程里包含了直接主管审批时展示选择组织
        departmentId: '', //组织id
        remark: '', //申请说明
        useCount: 1 //加盖次数
      },
      rules: {
        title: [{ required: true, message: this.$t('必填'), trigger: ['change'] }],
        sealType: [{ required: true, message: this.$t('必填'), trigger: ['change'] }],
        processId: [{ required: true, message: this.$t('必填'), trigger: ['change'] }],
        managerIds: [{ required: true, message: this.$t('必填'), trigger: ['change'] }],
        enterpriseName: [{ required: true, message: this.$t('必填'), trigger: ['change'] }],
        contractId: [{ required: true, message: this.$t('必填'), trigger: ['change'] }],
        type: [{ required: true, message: this.$t('必填'), trigger: ['change'] }]
      },
      electronList: [], //电子章列表
      contractList: [], //已选择的电子合同列表
      processList: [], //实体章的审批流程列表
      managerList: [], //已选择的审批人列表
      //当选取的审批流程里包含了直接主管审批时展示选择组织
      departmentList: [], //组织列表
      enterpriseList: [], //企业列表
      select: {
        title: '',
        show: false,
        list: [],
        value: 'value',
        label: 'label',
        filterable: true
      },
      picker: {
        show: false,
        type: '', //当前选择的时间字段
        data: []
      }
    }
  },
  mounted() {
    //查询企业列表
    this.getenterpriseList()
    //表单校验
    this.readyFn()
  },
  methods: {
    //回显
    echo(data) {
      this.form = {
        sealType: 'electron', //electron电子章，entity实体章
        title: data.title, //用章文件名
        enterpriseId: data.enterpriseId, //企业id
        enterpriseName: data.enterpriseName, //所属企业名
        sealId: data.sealId, //实体章id
        sealName: data.sealName, //实体章名
        contractId: data.contractId, //合同id
        type: 'process', //审批方式process为审批流程 user审批人
        processId: '', //审批流程id
        processName: '', //流程名称
        managerIds: '', //审批人ids
        isShowDepartment: true, //当选取的审批流程里包含了直接主管审批时展示选择组织
        departmentId: '', //组织id
        departmentName: '', //组织名称
        remark: '', //申请说明
        useCount: 1 //加盖次数
      }
      //console.log(data);
      //已选择的电子合同列表
      this.contractList = [data]
      //查询企业列表
      this.getenterpriseList()
      //获取电子章列表
      this.getElectronSealList()
    },
    //删除审批人
    delManagerList(key) {
      this.managerList = this.managerList.filter((res) => res.key !== key)
      this.form.managerIds = this.managerList.map((item) => item.key)
    },
    //接收电子章审批人
    data_audit(e) {
      this.managerList = e
      this.form.managerIds = e.map((item) => item.key)
    },
    //电子章审批人
    secrecy_seal(val) {
      if (val === '电子章审批人') {
        uni.navigateTo({
          url: `../../template/mailList/mailList?type=电子章审批人&sealId=${this.form.sealId}&enterpriseId=${this.form.enterpriseId}&data=${JSON.stringify(this.managerList)}`
        })
      }
    },
    //接收加盖印章
    data_cover(res) {
      this.form.device.push(res)
      //去重
      this.form.device = this.$lizhao.es6.arrayUnique(this.form.device, 'value')
    },
    //切换盖章类型
    changeSealType(data) {
      this.$emit('changeSealType', data)
    },
    //点击提交
    navigationBarButtonTap(e) {
      if (e.index === 0 && this.btnOnoff) {
        uni.showLoading({
          title: this.$t('提交中') + '...',
          mask: false
        })
        //点击提交
        this.submission()
      }
    },
    // onReady方法触发
    readyFn() {
      this.$refs.uForm.setRules(this.rules)
    },
    //提交
    submission() {
      if (this.form.useCount > 9999) {
        uni.showToast({
          title: this.$t('最大次数') + '9999',
          icon: 'none'
        })
        return
      }
      this.$refs.uForm.validate((valid) => {
        if (valid) {
          this.btnOnoff = false
          let req = {
            approvalIds: this.form.type === 'user' ? this.form.managerIds : [this.form.processId], //审批人(或审批流程)id列表
            contractId: this.form.contractId, //合同id
            enterpriseId: this.form.enterpriseId, //企业id
            departmentId: this.form.departmentId, //当审批流程有直接主管就要选择组织
            remark: this.form.remark,
            sealId: this.form.sealId, //加盖印章
            title: this.form.title, //用章文件名
            type: this.form.type, //审批方式 process:流程审批 user:用户审批
            useCount: this.form.useCount //印章加盖次数
          }
          this.$u
            .post(
              this.api
                .GLOBAL_electronic_enterprise_application_createEnterpriseElectronicSealApplication,
              req,
              { 'content-type': 'application/json;charset=UTF-8' }
            )
            .then((res) => {
              uni.hideLoading()
              if (res.code === 200) {
                uni.showToast({
                  title: this.$t(res.msg),
                  icon: 'success',
                  duration: 1000
                })
                setTimeout(() => {
                  uni.navigateBack({
                    delta: 1
                  })
                }, 1000)
              }
              this.btnOnoff = true
            })
        }
      })
    },
    //审批流程删除
    deleteAuditProcessFn() {
      this.form.departmentId = ''
      this.form.departmentName = ''
      this.form.processName = ''
      this.form.processId = ''
      this.form.isShowDepartment = false
      this.form.isShowDepartment = true
    },
    //选择select
    showSelect(title) {
      this.select.show = true
      this.select.title = title
      if (title === '加盖电子章') {
        this.select.list = this.electronList
        this.select.label = 'name'
        this.select.value = 'sealId'
      } else if (title === '选择审批流程') {
        this.select.list = this.processList
        this.select.label = 'name'
        this.select.value = 'id'
      } else if (title === '选择组织') {
        this.select.list = this.picker.data
        this.select.label = 'name'
        this.select.value = 'id'
      } else if (title === '所属企业') {
        this.select.list = this.enterpriseList
        this.select.label = 'name'
        this.select.value = 'id'
      }
    },
    //清空选项
    inputSelect(title) {
      if (title === '所属企业') {
        this.form.enterpriseId = '' //企业id
        this.form.enterpriseName = '' //所属企业名
        //清除电子合同
        this.clearContract()
      } else if (title === '加盖电子章') {
        this.form.sealId = ''
        this.form.sealName = ''
        //清空之前选择的审批人或者审批流程
        this.clearManager()
      }
    },
    //清除电子合同
    clearContract() {
      //清除电子合同
      this.form.contractId = ''
      this.contractList = []
      //清除电子章
      this.electronList = []
      this.form.sealId = ''
      this.form.sealName = ''
      //获取电子章列表
      this.getElectronSealList()
    },
    //清空之前选择的审批人或者审批流程
    clearManager() {
      //清空之前选择的审批人或者审批流程
      this.form.processId = ''
      this.form.processName = ''
      this.form.managerIds = ''
      this.managerList = []
      //获取流程数据
      this.getElectronOwner()
    },
    //确认选择select
    confirmSelet(e) {
      //console.log(e,this.select.title);
      if (!e[0].value) return
      if (this.select.title === '加盖电子章') {
        this.form.sealId = e[0].value
        this.form.sealName = e[0].label
        //清空之前选择的审批人或者审批流程
        this.clearManager()
      } else if (this.select.title === '所属企业') {
        //如果选的值没变则不需要清除电子合同
        if (this.form.enterpriseId !== e[0].value) {
          this.form.enterpriseId = e[0].value //企业id
          this.form.enterpriseName = e[0].label //所属企业名
          //清除电子合同
          this.clearContract()
        }
      } else if (this.select.title === '选择审批流程') {
        this.form.processId = e[0].value
        this.form.processName = e[0].label //所属企业名
        //查询用户所属组织列表
        this.getDepartmentsByLogin()
      }
    },
    //查询用户所属组织列表
    getDepartmentsByLogin() {
      this.$u
        .post(this.api.GLOBAL_auth_department_getDepartmentsByLogin, {
          page: false
        })
        .then((res) => {
          if (res.code === 200) {
            this.picker.data = res.data
            this.picker.show = true
          }
        })
    },
    //取消选取组织
    pickerCancel() {
      this.deleteAuditProcessFn()
    },
    //确认选取组织
    pickerConfirm(e) {
      this.form.departmentId = this.picker.data[e].id
      this.form.departmentName = this.picker.data[e].name
    },
    //选择电子合同
    addElectronContract() {
      uni.navigateTo({
        url: '../../electronicSeal/contractList/contractList',
        events: {
          confirm(data) {
            this.contractList = [data]
            this.form.contractId = data.contractId
            this.form.enterpriseId = data.enterpriseId
            this.form.enterpriseName = data.enterpriseName
            this.form.title = data.title
            //获取电子章列表
            this.getElectronSealList()
          }
        },
        success(res) {
          res.eventChannel.emit('pagePramas', { enterpriseId: this.form.enterpriseId })
        }
      })
    },
    //获取电子章列表
    getElectronSealList() {
      if (this.form.enterpriseId) {
        this.$u
          .get(
            this.api.GLOBAL_electronic_enterprise_application_findAvailableElectronicList +
              '/' +
              this.form.enterpriseId,
            { page: false }
          )
          .then((res) => {
            if (res.code === 200 && res.data) {
              this.electronList = res.data
            } else {
              this.electronList = []
            }
          })
      }
    },
    //删除盖章合同
    delContract(key) {
      //清除电子合同
      this.form.contractId = ''
      this.contractList = []
      //清除电子章
      this.electronList = []
      this.form.sealId = ''
      this.form.sealName = ''
      //清除企业
      this.form.enterpriseId = ''
      this.form.enterpriseName = ''
    },
    //获取电子章的流程数据
    getElectronOwner() {
      let req = {
        page: false,
        enterpriseId: this.form.enterpriseId,
        sealId: this.form.sealId
      }
      this.$u
        .get(this.api.GLOBAL_electronic_enterprise_application_findFlowList, req)
        .then((res) => {
          if (res.code === 200 && res.data) {
            this.processList = res.data
          } else {
            this.processList = []
          }
        })
    },
    //查询企业列表
    getenterpriseList() {
      let req = {
        page: false
      }
      this.$u.get(this.api.GLOBAL_electronic_enterprise_findList, req).then((res) => {
        if (res.code === 200 && res.data) {
          this.enterpriseList = res.data
        } else {
          this.enterpriseList = []
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.applicationSeal {
  background-color: #fff;
  height: 100%;
  box-sizing: border-box;
  padding: 0 30rpx;

  .submissionbtn {
    width: 100%;
    display: flex;
    justify-content: center;
    margin-top: 40rpx;
  }
}
</style>
